#!/usr/bin/env python
#-*- coding:utf-8 -*-

import os
import utils
import tempfile 
import config
from log import log
from mutagen.mp3 import MP3
import mutagen.id3
from mutagen.easyid3 import EasyID3


def print_audio_metadata(id3info):
    print
    print '%-13s\t%s' % ('Field', 'Value')
    print '-' * 70
    for k, v in id3info.items():
        print '%-13s\t%s' % (k, v and v[0])

def get_audio_metadata(uri):
    metadata = MP3(uri, ID3=EasyID3)
    title = metadata['title'][0] if metadata.has_key('title') else '未命名歌曲'
    artist = metadata['artist'][0] if metadata.has_key('artist') else '未知艺术家'
    album = metadata['album'][0] if metadata.has_key('album') else '未知专辑'

    return {'title': title, 'artist': artist, 'album': album }

def get_video_screenshot(uri):
    try:
        return get_video_screenshot_from_ffmpeg(uri)
    except Exception, e:
        log.warn('failed to retrieve screenshot for %s via ffmpeg: %s' % (uri, e))
        pass

    try:
        return get_video_screenshot_from_ffvideo(uri)
    except Exception, e:
        log.warn('failed to retrieve screenshot for %s via ffvideo: %s' % (uri, e))
        pass

    from imaging import imaging
    return imaging.defaultThumbnail()


def get_video_screenshot_from_ffmpeg(uri):
    ffmpegthumbnailor = '/usr/bin/ffmpegthumbnailer'
    if not os.path.exists(ffmpegthumbnailor):
        raise Exception('%s does not exist!' % ffmpegthumbnailor)
    
    (s, f) = tempfile.mkstemp(suffix='.jpeg')
    utils.runcmd('%s -s 0 -f -i %s -o %s' % (ffmpegthumbnailor, uri, f))
    data = open(f).read()
    os.unlink(f)

    return data

def get_video_screenshot_from_ffvideo(uri):
    from ffvideo import VideoStream

    vs = VideoStream(uri)
    ts = vs.duration/10
    frame = vs.get_frame_at_sec(ts)
    
    (s, f) = tempfile.mkstemp(suffix='.jpeg')
    frame.image().save(f)
    data = open(f).read()
    os.unlink(f)
    return data
    

def get_video_metadata(uri):
    try:
        from ffvideo import VideoStream
        vs = VideoStream(uri)

        return {
            'codec':    vs.codec_name,
            'duration': vs.duration,
            'width':    vs.frame_width,
            'height':   vs.frame_height,
            'title':    '未知视频',
        }
    except Exception, e:
        return {
            'codec':    None,
            'duration': 0,
            'width':    0,
            'height':   0,
            'title':    '未知视频',
        }


if __name__ == '__main__':
    get_audio_metadata(os.path.join(config.STATIC_DIR, 'audio/sample.mp3'))

    with open('/tmp/test.jpeg', 'w') as f:
        f.write(get_video_screenshot(os.path.join(config.STATIC_DIR, 'video/sample.mp4')))
        f.close()
